package com.example.controller;

import lombok.SneakyThrows;
import xyz.lwm.lazycat.web.annocation.Controller;
import xyz.lwm.lazycat.web.annocation.Get;
import xyz.lwm.lazycat.web.annocation.Post;
import xyz.lwm.lazycat.web.handle.HttpRequest;
import xyz.lwm.lazycat.web.handle.HttpResponse;
import xyz.lwm.lazycat.web.handle.Multipart;

import java.io.ByteArrayInputStream;
import java.util.List;
import java.util.Map;

/**
 * 文件上传
 *
 * @author lwm
 */
@Controller("files")
public class FilesController {

    /**
     * 文件上传, 用 HttpRequest 取文件
     *
     * @param request http request
     */
    @SneakyThrows
    @Post("upload")
    public void uploadFile(HttpRequest request) {
        // 获取首个文件
        Multipart.File file = request.getMultipart().getFile("file");
        byte[] fileContent = file.getFileContent();
        System.out.println(file.size());
        // 获取文件列表
        List<Multipart.File> fileList = request.getMultipart().getFileList("file");
        // 获取参数列表
        Map<String, List<Multipart.File>> fileListMap = request.getMultipart().getFileListMap();
    }

    /**
     * 文件下载
     *
     * @param response http response
     */
    @Get("download")
    public void downloadFile(HttpResponse response) {
        String content = "大江东去浪淘尽，千古风流人物";
        String fileName = "file.txt";
        byte[] bytes = content.getBytes();
        response.write(new ByteArrayInputStream(bytes), bytes.length, "application/txt", fileName);
    }

}
